package laba7.taskB;

import interfaces.task7.executor.SumTask;
import java.math.BigInteger;
import java.util.Random;

/**
 * Class for adding large numbers.
 *
 * @author yakimovich
 */
public class SumTaskImpl implements SumTask {

	/**
	 * The number of BigInteger for sum.
	 */
	private int count;
	/**
	 * The max value.
	 */
	private long max;
	/**
	 * The number of attempts.
	 */
	private int tryCount;

	/**
	 * The method sets count of numbers.
	 *
	 * @param i
	 *            count of number
	 */
	@Override
	public void setCount(int i) {
		if (i < 0) {
			throw new IllegalArgumentException(
			"The count value  can not be a negative number");
		}
		this.count = i;
	}

	/**
	 * The method sets value of max for numbers.
	 *
	 * @param l
	 *            value of max for numbers.
	 */
	@Override
	public void setMax(long l) {
		if (l <= 0) {
			throw new IllegalArgumentException(
			"The max value must be a positive number");
		}
		this.max = l;
	}

	/**
	 * The method generates a random BigInteger.
	 *
	 * @return a random BigInteger
	 */
	@Override
	public BigInteger getRandom() {
		BigInteger result;
		Random rnd = new Random();
		int maxNumBitLength = (int) (Math.log(max) / Math.log(2));
		result = new BigInteger(maxNumBitLength, rnd);
		return result;
	}

	/**
	 * The method for find sum of BigIntegers.
	 *
	 * @return the sum of the BigIntegers
	 */
	@Override
	public BigInteger getResult() {
		BigInteger result = BigInteger.ZERO;
		for (int i = 0; i < count; i++) {
			BigInteger b = getRandom();
			result = result.add(b);
			System.out.println(result);
		}
		return result;
	}

	/**
	 * The method returns return the number of try count.
	 *
	 * @return the number of try count
	 */
	@Override
	public int getTryCount() {
		return tryCount;
	}

	/**
	 * The method increments tryCount.
	 */
	@Override
	public void incTryCount() {
		tryCount++;
	}

	/**
	 * The method for adding BigIntegers.
	 *
	 * @return true if adding is successful and false if adding is failed
	 * @throws Exception
	 *             when adding is failed and tryCount is 5
	 */
	@Override
	public boolean execute() throws Exception {
		boolean isSuccess;
		if (getResult().compareTo(BigInteger.ZERO) >= 0) {
			isSuccess = true;
		} else {
			isSuccess = false;
                    throw new Exception("This Task is failed");
		}
		System.out.println("Summ: " + isSuccess);
		return isSuccess;
	}
}